<template>
  <el-drawer size="514" class="jzt-drawer change_order_modal" v-model="_isOpen" @close="cancelClick">
    <template #header>
      <span class="modal_title">创建变更售后单</span>
    </template>
    <el-form ref="formRef" class="modal_form" label-position="top" :model="formdata" :rules="rules">
      <el-form-item class="form_box" label="">
        <span v-if="formdata.customerTotalCollectionAmount < 0">需客户收款金额合计:</span>
        <span v-else>需客户支付金额合计:</span>
        <el-input v-model.number="formdata.customerCompensationAmount" @input="handleInput" placeholder="请输入数字"></el-input>
        <div class="form_price mt20">
          <span>报价变更单合计：￥{{ formdata.quoteChangeAmount }}</span>
          <span>
            需客户支付合计：<span class="price_high">¥{{ Math.abs(formdata.customerTotalCollectionAmount) || 0.0 }}</span>
          </span>
        </div>
      </el-form-item>

      <el-form-item label="变更分类" prop="rectificationValue">
        <el-cascader
          v-model="formdata.rectificationValue"
          :options="rectificationOptions"
          :props="treeRectification"
          clearable
          @change="handleRectification"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="变更原因" prop="reasontreeValue">
        <el-cascader
          v-model="formdata.reasontreeValue"
          :options="reasontreeData"
          :props="treeDatePropsclearable"
          clearable
          @change="handleChangeReason"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="是否业主可见">
        <el-radio-group v-model.number="formdata.isVisible" prop="isVisible">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否需业主确认" prop="isOwnerConfirmationRequired">
        <el-radio-group v-model.number="formdata.isOwnerConfirmationRequired" :disabled="isNeedsure">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否首次收款后开展任务和核量" prop="isFirstPaymentReceived">
        <el-radio-group v-model.number="formdata.isFirstPaymentReceived" :disabled="isFirststart">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="变更模版">
        <el-select v-model="formdata.packageId" placeholder="请选择" prop="packageId">
          <el-option v-for="item in templateOptions" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
        </el-select>
      </el-form-item>

      <el-form-item :label="`变更内容`" class="item_table_active input-container" prop="reformDesc">
        <template #label>变更内容<a href="#" @click="handleStandard">申请标准</a></template>
        <el-input style="width: 100%" v-model="formdata.reformDesc" type="textarea" :placeholder="`变更内容`" />
      </el-form-item>

      <el-form-item label="工艺标准图" prop="picIdLen">
        <div>
          <!-- 上传图片 -->
          <el-upload
            class="upload-demo upload-card"
            v-model:file-list="imgFileList"
            :disabled="FileList.length >= 9"
            ref="uploadImg"
            :show-file-list="true"
            multiple
            :limit="9"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon(file, fileList);
              }
            "
          >
            <div :class="{ notuse: FileList.length >= 9 ? true : false }">
              <el-icon class="f24"><Plus /></el-icon>
              <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
            </div>

            <template #file="{ file }">
              <div>
                <img v-show="file.img" class="el-upload-list__item-thumbnail" :src="file.img" alt="" />
                <span v-show="!file.img" class="f30">
                  <el-icon><Loading /></el-icon>
                </span>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <p class="f12 mt10" style="color: #86909c">只能上传jpg/png，且不超过10M,最大支持上传9张</p>
        </div>
      </el-form-item>

      <el-form-item label="工艺标准视频" prop="videoIdLen">
        <div>
          <!-- 上传图片 -->
          <el-upload
            class="upload-demo upload-card upload-video"
            v-model:file-list="videoListEdit"
            :disabled="videoList.length >= 6"
            ref="uploadVideo"
            :show-file-list="true"
            multiple
            :limit="8"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon(file, fileList, 'video');
              }
            "
          >
            <div :class="{ notuse: videoList.length >= 6 ? true : false }">
              <el-icon class="f24"><Plus /></el-icon>
              <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
            </div>

            <template #file="{ file }">
              <div>
                <!-- <img v-show="file.img" class="el-upload-list__item-thumbnail" :src="file.img" alt="" /> -->
                <video controls style="width: 100%; height: 100%" v-if="file.video">
                  <source :src="file.video" type="video/mp4" />
                  对不起，您的浏览器不支持播放视频文件
                </video>
                <span v-show="!file.video" class="f30">
                  <el-icon><Loading /></el-icon>
                </span>
                <span class="el-upload-list__item-actions" v-show="optionInfo.type !== 'view'">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file, 'video')">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <!-- avi/mov/mp4/wmv -->
          <p class="f12 mt10" style="color: #86909c">只能上传 mp4 文件格式，单个不超过200MB，最大支持6个</p>
        </div>
      </el-form-item>
    </el-form>

    <!-- 申请标准 start-->
    <div class="application-dialog">
      <el-dialog v-model="isShowApplicationDialog" width="544px" :show-close="false" @close="handelApplicationCancel">
        <template #header>
          <title-view title="申请标准" isClose @close="handelApplicationCancel" />
        </template>
        <el-form :model="applicationForm" v-if="isShowApplicationDialog" v-loading="isLoadingInfo">
          <el-form-item label="汇报标准">
            <el-input v-model="applicationForm.standardDesc" type="textarea" disabled :autosize="{ minRows: 4 }" />
          </el-form-item>
          <el-form-item label="上传图片">
            <image-video-upload :file-list="applicationPicData" disabled />
          </el-form-item>
          <el-form-item label="上传视频">
            <image-video-upload :file-list="applicationVideoData" disabled fileType="video" />
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <div class="foot_footright">
      <div class="foot_footright_cancle" @click="handleCancel">
        <div class="text">取消</div>
      </div>
      <div class="foot_footright_sure" @click="handleSubmit">
        <div class="text">提交</div>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, computed, defineEmits } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  rectificationTypeTree,
  rectificationStandard,
  serviceReasonTypeTree,
  templateType,
  reformDetail,
  addreform
} from "@/apis/quote-price/following";

const props = defineProps({
  modelValue: () => false,
  afterSalesType: { type: Number, default: 1 }
});
const _isOpen = computed({
  get: () => props.modelValue,
  set: newVal => emits("update:modelValue", newVal)
});
const emits = defineEmits(["update:modelValue", "cancel", "submit"]);
const cancelClick = () => {
  emits("update:modelValue", false);
};

const uploadImg = ref();
const uploadVideo = ref();
const FileList = ref([]); //商品图片list
const imgFileList = ref([]); //编辑时商品图片list
const videoList = ref([]); //商品视频list
const videoListEdit = ref([]); //编辑时商品视频list

const showtitle = ref("");
const router = useRouter();
const route = useRoute();
const formdata = ref({
  reasonIds: [],
  isVisible: 1,
  customerTotalCollectionAmount: 0,
  quoteChangeAmount: 0,
  customerCompensationAmount: 0
});
const picData = ref([]);
const videoData = ref([]);
const templateOptions = ref([]);
const rectificationOptions = ref([]);
const treeRectification = ref({
  multiple: false,
  label: "reformTypeName",
  value: "reformTypeId",
  children: "children"
});
const reasontreeData = ref([]);
const treeDatePropsclearable = ref({
  multiple: false,
  label: "reasonName",
  value: "reasonId",
  children: "children"
});

const ruleFormRef = ref(null);
const rules = {
  rectificationValue: [{ required: true, message: "请选择分类", trigger: "change" }],
  isVisible: [{ required: true, message: "请选择是否业主可见", trigger: "change" }],
  reasontreeValue: [{ required: true, message: "请选择原因", trigger: "change" }],
  isOwnerConfirmationRequired: [{ required: true, message: "请选择是否需要业主确认", trigger: "blur" }],
  packageId: [{ required: true, message: "请选择模板", trigger: "blur" }],
  isFirstPaymentReceived: [{ required: true, message: "请选择是否首次收款后开展任务和核量", trigger: "blur" }],
  reformDesc: [{ required: true, message: "内容不能为空", trigger: "blur" }]
};
//表格状态0是创建，1是修改
const reformState = ref("0");
const isShowApplicationDialog = ref(false);
const isLoadingInfo = ref(false);
const applicationPicData = ref([]);
const applicationVideoData = ref([]);
const initApplicationForm = {
  standardDesc: "",
  picUrls: "",
  picIds: "",
  videoUrls: "",
  videoIds: ""
};
const isNeedsure = ref(false);
const isFirststart = ref(false);
const resultForm = ref({});
const applicationForm = ref({ ...initApplicationForm });
const handleInput = value => {
  const validValue = value.match(/^\d*(\.\d{0,2})?/) ? value.match(/^\d*(\.\d{0,2})?/)[0] : "";
  formdata.value.customerCompensationAmount = validValue;
  getTotal();
};
const getTotal = () => {
  if (formdata.value.customerCompensationAmount == "") {
    formdata.value.customerTotalCollectionAmount = parseFloat(formdata.value.quoteChangeAmount);
    return isNaN(formdata.value.customerTotalCollectionAmount) ? "0.00" : formdata.value.customerTotalCollectionAmount;
  }
  formdata.value.customerTotalCollectionAmount =
    parseFloat(formdata.value.quoteChangeAmount) - parseFloat(formdata.value.customerCompensationAmount);
  return isNaN(formdata.value.customerTotalCollectionAmount) ? "0.00" : formdata.value.customerTotalCollectionAmount;
};

// 调用顺序执行功能的函数
const executeFunctionsInOrder = async () => {
  try {
    // 按顺序等待每个函数完成
    await getRectificationTypeTree();
    await gettemplateType();
    await getserviceReasonTypeTree();
    // 检查条件并执行另一个异步函数
    if (route.query.reformId) {
      reformState.value = "1";
      await getreformDetail();
    }
  } catch (error) {
    console.error("Error executing functions:", error);
  }
};

//获取表单数据
const getreformDetail = async () => {
  const { data } = await reformDetail(route.query.reformId);
  formdata.value = {
    ...data
  };
  formdata.value.reasontreeValue = findParentIds(reasontreeData.value, data.reasonList?.[0]?.reasonId ?? null, "reasonId");
  formdata.value.rectificationValue = findParentIds(rectificationOptions.value, data.reformTypeId, "reformTypeId");
  videoData.value = parseMediaData(data.videoIds, data.videoUrls);
  picData.value = parseMediaData(data.picIds, data.picUrls);
};
//递归查找父id
const findParentIds = (nodes, targetId, key) => {
  const path = [];
  const search = nodeList => {
    for (const node of nodeList) {
      path.push(node[key]);
      if (node[key] === targetId) {
        return true;
      }
      if (node.children && search(node.children)) {
        return true;
      }
      path.pop();
    }
    return false;
  };
  search(nodes);
  return path;
};
// 函数用于将逗号分隔字符串转换为对象数组
const parseMediaData = (ids, urls) => {
  const idArray = ids ? ids.split(",") : [];
  const urlArray = urls ? urls.split(",") : [];
  if (idArray.length !== urlArray.length) {
    console.warn("ID 和 URL 数量不匹配");
  }
  return idArray.map((id, index) => ({
    fileId: id,
    fileUrl: urlArray[index] || "" // 防止访问 undefined
  }));
};

//选择分类
const handleRectification = e => {
  formdata.value.reformTypeId = e[e.length - 1];
  resetRideo(formdata.value.reformTypeId);
};
//重置分类信息
const resetRideo = async e => {
  const { data } = await rectificationStandard(e);
  if (data.taskPackageList.length > 1) {
    templateOptions.value = data.taskPackageList;
  } else {
    gettemplateType();
  }
  // 判断 isConfirm
  isNeedsure.value = Boolean(data.isConfirm);
  formdata.value.isOwnerConfirmationRequired = data.isConfirm !== null ? (data.isConfirm ? 1 : 0) : "";

  // 判断 afterPay
  isFirststart.value = Boolean(data.afterPay);
  formdata.value.isFirstPaymentReceived = data.afterPay !== null ? (data.afterPay ? 1 : 0) : "";
};
//申请标准
const handleStandard = () => {
  getrectificationStandard(formdata.value.reformTypeId);
};
//获取申请标准
const getrectificationStandard = async value => {
  if (!value) return;
  isShowApplicationDialog.value = true;
  try {
    isLoadingInfo.value = true;
    const { data } = await rectificationStandard(value);
    handelDetailData(data);
    applicationForm.value = data ?? {};
    isLoadingInfo.value = false;
  } catch (err) {
    isLoadingInfo.value = false;
  }
};
const handelDetailData = data => {
  const picUrls = data.picUrls ? data.picUrls.split(",") : [];
  const picIds = data.picIds ? data.picIds.split(",") : [];
  const videoUrls = data.videoUrls ? data.videoUrls.split(",") : [];
  const videoIds = data.videoIds ? data.videoIds.split(",") : [];
  applicationPicData.value = picUrls.map((item, index) => {
    return {
      fileUrl: item,
      fileName: "",
      fileId: picIds[index]
    };
  });
  applicationVideoData.value = videoUrls.map((item, index) => {
    return {
      fileUrl: item,
      fileName: "",
      fileId: videoIds[index]
    };
  });
};

//关闭申请标准
const handelApplicationCancel = () => {
  isShowApplicationDialog.value = false;
  applicationForm.value = { ...initApplicationForm };
  applicationPicData.value = [];
  applicationVideoData.value = [];
};
//选择原因
const handleChangeReason = e => {
  formdata.value.reasonIds = e[e.length - 1];
};
//取消
const handleCancel = () => {
  ElMessageBox.confirm("关闭后当前录入信息不保存，确认关闭？", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      // window.close();
      router.go(-1);
    })
    .catch(err => {
      console.log(err);
    });
};
//提交
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(valid => {
    if (valid) {
      resultForm.value = {
        ...formdata.value
      };
      delete resultForm.value.rectificationValue;
      delete resultForm.value.reasontreeValue;
      submitSuccess();
    } else {
      console.log("提交失败，请检查输入内容");
      return false;
    }
  });
};
//提交
const submitSuccess = () => {
  if (picData.value) {
    const picIds = picData.value.map(item => item.fileId).join(",");
    const picUrls = picData.value.map(item => item.fileUrl).join(",");
    Object.assign(resultForm.value, { picIds, picUrls });
  }
  if (videoData.value) {
    const videoIds = videoData.value.map(item => item.fileId).join(",");
    const videoUrls = videoData.value.map(item => item.fileUrl).join(",");
    Object.assign(resultForm.value, { videoIds, videoUrls });
  }
  if (reformState.value === "0") {
    Object.assign(resultForm.value, {
      contractId: route.query.contractId,
      customerId: route.query.customerId,
      afterSalesType: props.afterSalesType,
      quoteChangeAmount: 0,
      customerCompensationAmount: 0,
      exchangeBudgetId: ""
    });
    addformdata(resultForm.value);
  } else {
    Object.assign(resultForm.value, {
      quoteChangeAmount: 0,
      customerCompensationAmount: 0,
      exchangeBudgetId: ""
    });
    updatareform(route.query.reformId, resultForm.value).then(res => {
      ElMessage.success("更新成功");
    });
  }
};

const addformdata = async resultForm => {
  const { data } = await addreform(resultForm);
  ElMessage.success("新增成功");
};
//分类选项
const getRectificationTypeTree = async () => {
  const { code, data } = await rectificationTypeTree(props.afterSalesType);
  code == 200 && (rectificationOptions.value = data);
};
//模板选项
const gettemplateType = async () => {
  const { code, data } = await templateType(props.afterSalesType);
  code == 200 && (templateOptions.value = data);
};

//原因选项
const getserviceReasonTypeTree = async () => {
  const { code, data } = await serviceReasonTypeTree(props.afterSalesType);
  code == 200 && (reasontreeData.value = data);
};

executeFunctionsInOrder();
</script>
<style lang="scss">
.change_order_modal {
  .el-drawer__header {
    margin-bottom: 0;
  }
  .el-form-item__label {
    color: #4e5969;
  }
  .modal_title {
    font-size: 18px;
    line-height: 24px;
    color: #131414;
  }
  .modal_form {
    .form_box {
      padding: 20px;
      background: #f6f8fa;
      border-radius: 10px 0px 0px 10px;
      .form_price {
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: #606266;
        .price_high {
          color: #ff3333;
        }
      }
      .el-input__wrapper {
        background: white !important;
      }
    }
    .form_title {
      display: flex;
      justify-content: space-between;
      .title_text {
        font-size: 18px;
        line-height: 24px;
      }
      .title_opreate {
        color: #213270;
      }
    }
    .img_upload {
      box-sizing: border-box;
      padding: 10px;
      width: 80px;
      height: 80px;
      background: #f2f3f5;
      text-align: center;
      color: #c9cdd4;
    }
    .video_upload {
      box-sizing: border-box;
      padding: 10px;
      width: 200px;
      height: 120px;
      background: #f2f3f5;
      text-align: center;
      color: #c9cdd4;
    }
  }
}

// 申请标准
.application-dialog {
  :deep(.el-form) {
    margin-top: 24px;
  }

  :deep(.el-input.is-disabled .el-input__wrapper),
  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    border: 1px solid #f2f3f5;
    box-shadow: none;
    background-color: #fff !important;
    color: #3d3d3d;
    width: 400px;
  }

  .el-input.is-disabled :deep(.el-input__inner) {
    color: #1a1a1a !important;
    -webkit-text-fill-color: #1a1a1a !important;
    font-size: 14px;
    line-height: 22px;
  }
}
</style>
